package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.traceability.Batches;
import com.zbkj.common.model.traceability.TraceabilityLogs;
import com.zbkj.common.model.traceability.TraceableItems;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.traceability.TraceabilityLogsPageRequest;
import com.zbkj.common.request.traceability.TraceabilityLogsRequest;
import com.zbkj.service.dao.traceability.TraceabilityLogsDao;
import com.zbkj.service.service.BatchesService;
import com.zbkj.service.service.TraceabilityLogsService;
import com.zbkj.service.service.TraceableItemsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 追溯日志Service实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: xiaolic
 * +----------------------------------------------------------------------
 */
@Service
public class TraceabilityLogsServiceImpl extends ServiceImpl<TraceabilityLogsDao, TraceabilityLogs> implements TraceabilityLogsService {

    @Resource
    private TraceabilityLogsDao traceabilityLogsDao;
    
    @Autowired
    private BatchesService batchesService;

    @Autowired
    private TraceableItemsService traceableItemsService;

    /**
     * 分页查询追溯日志列表
     * @param request 分页请求参数
     * @return 分页结果
     */
    @Override
    public PageInfo<TraceabilityLogs> getPageList(TraceabilityLogsPageRequest request) {
        LambdaQueryWrapper<TraceabilityLogs> queryCount = new LambdaQueryWrapper<>();
        queryCount.eq(TraceabilityLogs::getIsDeleted, 0);
        queryCount.eq(TraceabilityLogs::getTraceableItemId, request.getTraceableItemId());
        Integer count = traceabilityLogsDao.selectCount(queryCount);

        LambdaQueryWrapper<TraceabilityLogs> queryWrapper = new LambdaQueryWrapper<>();

        // 只查询未删除的数据
        queryWrapper.eq(TraceabilityLogs::getIsDeleted, 0);

        // 按照日志标题模糊查询
        if (request.getLogTitle() != null && !request.getLogTitle().isEmpty()) {
            queryWrapper.like(TraceabilityLogs::getLogTitle, request.getLogTitle());
        }
        // 按照日志时间范围查询
        if (request.getLogTimeStart() != null) {
            queryWrapper.ge(TraceabilityLogs::getLogTime, request.getLogTimeStart());
        }
        if (request.getLogTimeEnd() != null) {
            queryWrapper.le(TraceabilityLogs::getLogTime, request.getLogTimeEnd());
        }

        if (count > 0) {
            queryWrapper.eq(TraceabilityLogs::getTraceableItemId, request.getTraceableItemId());
        } else {
            queryWrapper.eq(TraceabilityLogs::getBatchId, request.getBatchId());
            queryWrapper.isNull(TraceabilityLogs::getTraceableItemId);
        }

        // 按照排序字段升序
        queryWrapper.orderByAsc(TraceabilityLogs::getSortOrder);
        // 默认按日志时间升序
        queryWrapper.orderByAsc(TraceabilityLogs::getLogTime);

        // 分页查询
        Page<TraceabilityLogs> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<TraceabilityLogs> traceabilityLogs = traceabilityLogsDao.selectList(queryWrapper);

        if (CollUtil.isEmpty(traceabilityLogs)) {
            return CommonPage.copyPageInfo(page, CollUtil.newArrayList());
        }

        // 使用新的restPage方法将IPage转换为CommonPage
        return CommonPage.copyPageInfo(page, traceabilityLogs);
    }

    /**
     * 创建追溯日志
     * @param request 创建请求参数
     * @return 创建结果
     */
    @Override
    public Boolean create(TraceabilityLogsRequest request) {
        // 验证批次是否存在
        Batches batch = batchesService.getDetail(request.getBatchId());
        if (batch == null) {
            throw new AppException("关联的批次不存在");
        }

        // 如果指定了可追溯项ID，验证可追溯项存在
        if (request.getTraceableItemId() != null) {
            TraceableItems item = traceableItemsService.getDetail(request.getTraceableItemId());
            if (item == null) {
                throw new AppException("可追溯项不存在");
            }
        }

        // 创建日志
        TraceabilityLogs log = new TraceabilityLogs();
        BeanUtils.copyProperties(request, log);
        log.setCreatedAt(new Date());
        log.setUpdatedAt(new Date());
        
        return save(log);
    }

    /**
     * 更新追溯日志
     * @param request 更新请求参数
     * @return 更新结果
     */
    @Override
    public Boolean update(TraceabilityLogsRequest request) {
        if (request.getId() == null) {
            throw new AppException("日志ID不能为空");
        }
        
        // 查询原有日志
        TraceabilityLogs oldLog = getDetail(request.getId());
        if (oldLog == null) {
            throw new AppException("日志不存在");
        }
        
        // 验证批次是否存在
        if (!oldLog.getBatchId().equals(request.getBatchId())) {
            Batches batch = batchesService.getDetail(request.getBatchId());
            if (batch == null) {
                throw new AppException("关联的批次不存在");
            }
        }

        // 验证批次项目是否存在
        if (request.getTraceableItemId() != null
        && !Objects.equals(oldLog.getTraceableItemId(), request.getTraceableItemId())) {
            TraceableItems item = traceableItemsService.getDetail(request.getTraceableItemId());
            if (item == null) {
                throw new AppException("可追溯项不存在");
            }
        }
        
        // 更新日志
        TraceabilityLogs log = new TraceabilityLogs();
        BeanUtils.copyProperties(request, log);
        log.setUpdatedAt(new Date());
        
        return updateById(log);
    }

    /**
     * 删除追溯日志
     * @param id 日志ID
     * @return 删除结果
     */
    @Override
    public Boolean delete(Long id) {
        return removeById(id);
    }

    /**
     * 获取追溯日志详情
     * @param id 日志ID
     * @return 日志详情
     */
    @Override
    public TraceabilityLogs getDetail(Long id) {
        LambdaQueryWrapper<TraceabilityLogs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TraceabilityLogs::getId, id);
        queryWrapper.eq(TraceabilityLogs::getIsDeleted, 0);
        return getOne(queryWrapper);
    }

    /**
     * 根据批次ID获取对应的所有日志
     * @param batchId 批次ID
     * @return 日志列表
     */
    @Override
    public List<TraceabilityLogs> getLogsByBatchId(Long batchId) {
        LambdaQueryWrapper<TraceabilityLogs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TraceabilityLogs::getBatchId, batchId);
        queryWrapper.eq(TraceabilityLogs::getIsDeleted, 0);
        // 按照排序字段升序
        queryWrapper.orderByAsc(TraceabilityLogs::getSortOrder);
        // 默认按日志时间升序
        queryWrapper.orderByAsc(TraceabilityLogs::getLogTime);
        
        return traceabilityLogsDao.selectList(queryWrapper);
    }

    /**
     * 根据可追溯项ID或批次ID获取对应的所有日志
     * @param traceableItemId 可追溯项ID
     * @param batchId 批次ID
     * @return 日志列表
     */
    @Override
    public List<TraceabilityLogs> getLogsByTraceableItemIdOrBatchId(Long traceableItemId, Long batchId) {
        LambdaQueryWrapper<TraceabilityLogs> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(TraceabilityLogs::getIsDeleted, 0);
        countWrapper.eq(TraceabilityLogs::getTraceableItemId, traceableItemId);
        Integer count = traceabilityLogsDao.selectCount(countWrapper);

        LambdaQueryWrapper<TraceabilityLogs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TraceabilityLogs::getIsDeleted, 0);
        if (count > 0) {
            queryWrapper.eq(TraceabilityLogs::getTraceableItemId,  traceableItemId);
        } else {
            queryWrapper.eq(TraceabilityLogs::getBatchId, batchId);
            queryWrapper.isNull(TraceabilityLogs::getTraceableItemId);
        }
        // 按照排序字段升序
        queryWrapper.orderByAsc(TraceabilityLogs::getSortOrder);
        // 默认按日志时间升序
        queryWrapper.orderByAsc(TraceabilityLogs::getLogTime);

        return traceabilityLogsDao.selectList(queryWrapper);
    }
}
